﻿using Dapper;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OMG.Fill.Mulberry.Model;
using OMG.Fill.Mulberry.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace OMG.Fill.Mulberry.Service
{
    /// <summary>
    /// 表1桑园面积统计表T_MulAreaStatist通用操作类
    /// </summary>
    public class MulAreaStatistServices : MulAreaStatists
    {
        ReportServices rs = new ReportServices();
        public Pager<List<MulAreaStatistEntity>> GetPageList(MulAreaStatistQuery query)
        {
            Pager<List<MulAreaStatistEntity>> obj = new Pager<List<MulAreaStatistEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.T_MulAreaStatist where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<MulAreaStatistEntity>(strSql, paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取表1桑园面积统计表T_MulAreaStatist分页列表失败", ex);
                return obj;
            }
        }


        public ResResult<int> UpdateInfo(List<MulAreaStatistEntity> list)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.T_MulAreaStatist set ";
            strSql += "ReportId = @ReportId,";
            strSql += "NowMulArea = @NowMulArea,";
            strSql += "IntoMulArea = @IntoMulArea,";
            strSql += "NewPlantMulArea = @NewPlantMulArea,";
            strSql += "HighMulArea = @HighMulArea";
            strSql += " where Id = @Id";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    if (list.Count > 0)
                    {
                        string strRep = "update dbo.T_Report set Status=2 where Id=@ReportId";
                        dbCon.Execute(strRep, new { ReportId = list[0].ReportId }, trans);
                    }
                    int result = dbCon.Execute(strSql, list, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "更新成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;

                }
                catch (Exception ex)
                {
                    //出现异常，事务Rollback
                    trans.Rollback();
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("更新表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
        }

        /// <summary>
        /// 获取填报数据
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns></returns>
        public ResResult<List<MulAreaStatistEntity>> GetInfo(string reportId)
        {
            ResResult<List<MulAreaStatistEntity>> obj = new ResResult<List<MulAreaStatistEntity>>();
            //判定是否生成过报表
            if (CheckRepCount(reportId))
            {
                //获取报表内容(报编号，查询状态:0为初始化状态,1为已被初始化从初始化表读列表)
                List<MulAreaStatistEntity> templist = GetTabContent(reportId, 0);
                try
                {
                    if (AddInfo(templist) > 0)
                    {
                        obj.model = templist;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "初始化并且返回数据成功！";
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("新增表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                    obj.message = "返回数据成功！";
                }
            }
            else
            {
                try
                {
                    //获取报表内容(报编号，查询状态:0为初始化状态,1为已被初始化从初始化表读列表)
                    List<MulAreaStatistEntity> templist = GetTabContent(reportId, 1);
                    obj.model = templist;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "返回数据成功！";
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("新增表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                    obj.message = "返回数据成功！";
                }
            }
            return obj;
        }

        /// <summary>
        /// 初始化报表内容
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int AddInfo(List<MulAreaStatistEntity> list)
        {
            string strSql = @"INSERT INTO dbo.T_MulAreaStatist";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "NowMulArea,";
            strSql += "IntoMulArea,";
            strSql += "NewPlantMulArea,";
            strSql += "HighMulArea)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@NowMulArea,";
            strSql += "@IntoMulArea,";
            strSql += "@NewPlantMulArea,";
            strSql += "@HighMulArea)";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                try
                {
                    int result = dbCon.Execute(strSql, list);
                    dbCon.Dispose();//数据库连接释放
                    return DefaultKey.SuccessResult;
                }
                catch (Exception ex)
                {
                    LogHelper.ErrorLog("新增表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                    dbCon.Dispose();//数据库连接释放
                    return DefaultKey.ErrorResult;

                }
            }
        }

        /// <summary>
        /// 判定是否生成过报表
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns>没生成过true,否则false</returns>
        public bool CheckRepCount(string reportId)
        {
            string strSql = @"select count(1) from dbo.T_MulAreaStatist where ReportId=@ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportId = reportId }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("判断是否生成过表1桑园面积统计表T_MulAreaStatist失败", ex);
                return false;
            }
        }

        /// <summary>
        /// 获取报表内容
        /// </summary>
        /// <param name="reportId"></param>
        /// <param name="edittype">0的时候返回视图列表，不为0的时候返回数据库列表</param>
        /// <returns></returns>
        public List<MulAreaStatistEntity> GetTabContent(string reportId, int edittype)
        {
            List<MulAreaStatistEntity> obj = new List<MulAreaStatistEntity>();
            string strSql = "";
            if (edittype == 0)
            {
                strSql = @"select * from dbo.T_MulAreaStatist order by SortCode asc,ItemCode asc";
            }
            else
            {
                strSql = @"select * from dbo.T_MulAreaStatist where ReportId='" + reportId + "' order by SortCode asc,ItemCode asc";
            }
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj = dbCon.Query<MulAreaStatistEntity>(strSql).ToList();
                    if (edittype == 0)
                    {
                        foreach (var item in obj)
                        {
                            item.ReportId = reportId;
                            item.Id = CustomFun.GetGuid();
                        }
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("获取表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                return obj;
            }
        }

        /// <summary>
        /// 获取指定对象
        /// </summary>
        public override ResResult<MulAreaStatistEntity> GetModel(string ReportId)
        {
            ResResult<MulAreaStatistEntity> obj = new ResResult<MulAreaStatistEntity>();
            MulAreaStatistEntity model = new MulAreaStatistEntity();
            if (CheckRepCount(ReportId))
            {
                model.ReportId = ReportId;
                if (AddInfo(model).status > 0)
                {
                    obj.model = model;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                }
            }
            else
            {
                string strSql = @"select * from dbo.T_MulAreaStatist where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        obj.model = dbCon.Query<MulAreaStatistEntity>(strSql, new { ReportId = ReportId }).FirstOrDefault();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "获取成功！";
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("获取表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);

                }
            }
            return obj;
        }


        /// <summary>
        /// 修改
        /// </summary>
        public ResResult<int> UpdateInfo(MulAreaStatistViewModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            ReportServices reportServices = new ReportServices();
            string strSql = @"UPDATE dbo.T_MulAreaStatist set ";
            strSql += "ReportId = @ReportId,";
            strSql += "NowMulArea = @NowMulArea,";
            strSql += "IntoMulArea = @IntoMulArea,";
            strSql += "NewPlantMulArea = @NewPlantMulArea,";
            strSql += "HighMulArea = @HighMulArea,";
            strSql += "MidMulArea = @MidMulArea,";
            strSql += "LowMulArea = @LowMulArea,";
            strSql += "NewlyMulArea = @NewlyMulArea,";
            strSql += "NotUseMulArea = @NotUseMulArea,";
            strSql += "DestroyMulArea = @DestroyMulArea ";
            strSql += " where Id = @Id";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    int result = dbCon.Execute(strSql, model, trans);
                    string strRep = "update dbo.T_Report set Status='2',UpdateTime=@UpdateTime where Id=@ReportId";
                    dbCon.Execute(strRep, new { ReportId = model.ReportId, UpdateTime = DateTime.Now }, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "更新成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("更新表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                    return obj;
                }
            }
        }

        /// <summary>
        /// 获取今往年数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<MulAreaStatistViewModel> GetModel(MulNowModel model)
        {
            ResResult<MulAreaStatistViewModel> obj = new ResResult<MulAreaStatistViewModel>();
            MulAreaStatistEntity vfEntity = new MulAreaStatistEntity();
            MulAreaStatistViewModel vvm = new MulAreaStatistViewModel();
            DictServices dictServices = new DictServices();
            var paramlist = new DynamicParameters();
            string strSqlReport = "";
            if (model != null)
            {
                if (!string.IsNullOrEmpty(model.AreaCode) && !string.IsNullOrEmpty(model.ReportCode) && !string.IsNullOrEmpty(model.FillInYear))
                {
                    string FillInYear = dictServices.GetKey(model.FillInYear);
                    paramlist.Add("AreaCode", model.AreaCode);
                    paramlist.Add("ReportCode", model.ReportCode);
                    paramlist.Add("FillInYear", FillInYear);
                    int OldFillInYear = Convert.ToInt32(FillInYear) - 1;
                    if (OldFillInYear < 0)
                    {
                        OldFillInYear = 0;
                    }
                    paramlist.Add("OldFillInYear", OldFillInYear.ToString());
                    string strNowSql = "SELECT r.Opinion , mas.Id,mas.ReportId,mas.DestroyMulArea,mas.HighMulArea,mas.IntoMulArea,mas.LowMulArea,mas.MidMulArea,mas.NewlyMulArea,mas.NewPlantMulArea,mas.NotUseMulArea,mas.NowMulArea,ReportCode,Status as ReportStatus "
                        + " FROM T_Report r LEFT JOIN T_MulAreaStatist mas ON r.Id = mas.ReportId WHERE ReportCode = @ReportCode and FillInYear = @FillInYear and AreaCode = @AreaCode ";
                    string strOldSql = "SELECT mas.Id as OldId,mas.ReportId as OldReportId,mas.DestroyMulArea as OldDestroyMulArea,mas.HighMulArea as OldHighMulArea,mas.IntoMulArea as OldIntoMulArea,mas.LowMulArea as OldLowMulArea,"
                        + "mas.MidMulArea as OldMidMulArea,mas.NewlyMulArea as OldNewlyMulArea,mas.NewPlantMulArea as OldNewPlantMulArea,mas.NotUseMulArea as OldNotUseMulArea,mas.NowMulArea as OldNowMulArea,ReportCode,Status as OldReportStatus "
                        + " FROM T_Report r LEFT JOIN T_MulAreaStatist mas ON r.Id = mas.ReportId WHERE ReportCode = @ReportCode and FillInYear = @OldFillInYear and AreaCode = @AreaCode ";
                    strSqlReport = "SELECT * FROM ((" + strNowSql + ")t left JOIN  (" + strOldSql + ")tt ON t.ReportCode = tt.ReportCode)";

                    Boolean currentResult = rs.CheckRepCreate(model.ReportCode, model.AreaCode, FillInYear);
                    Boolean OldResult = rs.CheckRepCreate(model.ReportCode, model.AreaCode, OldFillInYear.ToString());
                    //判断选择的年度与上一年度是否生成过报表
                    if (currentResult && OldResult)
                    {
                        obj.model = vvm;
                        obj.status = -1;
                        obj.message = model.FillInYear + "与上一年的报表没有填报数据！！";
                    }
                    //判断本年是否生成过报表
                    else if (currentResult)
                    {
                        var dbCon = ConnectFactory.GetOpenConnection();
                        obj.model = dbCon.Query<MulAreaStatistViewModel>(strOldSql, paramlist).FirstOrDefault();
                        obj.status = -2;
                        obj.message = model.FillInYear + "的报表没有填报数据！！";
                        dbCon.Dispose();//数据库连接释放
                    }
                    else
                    {
                        var dbCon = ConnectFactory.GetOpenConnection();
                        //获取报表Id
                        vfEntity.ReportId = rs.GetReportId(model.ReportCode, model.AreaCode, FillInYear);
                        //判断表T_VegFacility是否初始化过
                        if (CheckRepCount(vfEntity.ReportId))
                        {
                            if (AddInfo(vfEntity).status > 0)//报表初始化
                            {
                                //查询去年数据
                                obj.model = dbCon.Query<MulAreaStatistViewModel>(strOldSql, paramlist).FirstOrDefault();
                                obj.status = 1;//初始化成功status为1
                                obj.message = "MulAreaStatist报表初始化成功！";
                                return obj;
                            }
                        }
                        else
                        {
                            try
                            {
                                obj.model = dbCon.Query<MulAreaStatistViewModel>(strSqlReport, paramlist).FirstOrDefault();
                                obj.status = 2;//成功状态为2
                                obj.message = "获取MulAreaStatist报表今往年数据成功！";
                                return obj;
                            }
                            catch (Exception ex)
                            {
                                obj.status = 0; //失败状态
                                obj.message = ex.ToString().Trim();
                                LogHelper.ErrorLog("获取MulAreaStatist报表今往年数据失败", ex);
                            }
                        }
                    }
                }
            }
            return obj;
        }

        /// <summary>
        /// 读取导入的Excel数据
        /// </summary>
        /// <param name="pathName">导入文件路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="startRow">从第几行开始读取数据</param>
        /// <returns></returns>
        public List<MulAreaInfoModel> ExcelToModel(string pathName, string fileSuffix, string sheetName, int startRow)
        {

            IWorkbook workbook = null;
            ISheet sheet = null;
            List<MulAreaInfoModel> list = new List<MulAreaInfoModel>();
            FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
            switch (fileSuffix)
            {
                case ".xls":
                    workbook = new HSSFWorkbook(fs);
                    break;
                case ".xlsx":
                    workbook = new XSSFWorkbook(fs);
                    break;
                default:
                    workbook = new HSSFWorkbook(fs);
                    break;
            }
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                //获取有数据的行数
                int rowCount = 0;
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        rowCount = sheet.GetRow(i).RowNum;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int i = startRow; i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    MulAreaInfoModel model = new MulAreaInfoModel();
                    //if (row.GetCell(0) != null && row.GetCell(0).ToString() != "")
                    //{
                    //    model.NowMulArea = decimal.Parse(row.GetCell(0).ToString());
                    //}
                    //else
                    //{
                    //    model.NowMulArea = null;
                    //}
                    //if (row.GetCell(1) != null && row.GetCell(1).ToString() != "")
                    //{
                    //    model.IntoMulArea = decimal.Parse(row.GetCell(1).ToString());
                    //}
                    //else
                    //{
                    //    model.IntoMulArea = null;
                    //}
                    if (row.GetCell(2) != null && row.GetCell(2).ToString() != "")
                    {
                        model.HighMulArea = decimal.Parse(row.GetCell(2).ToString());
                    }
                    else
                    {
                        model.HighMulArea = null;
                    }
                    if (row.GetCell(3) != null && row.GetCell(3).ToString() != "")
                    {
                        model.MidMulArea = decimal.Parse(row.GetCell(3).ToString());
                    }
                    else
                    {
                        model.MidMulArea = null;
                    }
                    if (row.GetCell(4) != null && row.GetCell(4).ToString() != "")
                    {
                        model.LowMulArea = decimal.Parse(row.GetCell(4).ToString());
                    }
                    else
                    {
                        model.LowMulArea = null;
                    }
                    if (row.GetCell(5) != null && row.GetCell(5).ToString() != "")
                    {
                        model.NewlyMulArea = decimal.Parse(row.GetCell(5).ToString());
                    }
                    else
                    {
                        model.NewlyMulArea = null;
                    }
                    if (row.GetCell(6) != null && row.GetCell(6).ToString() != "")
                    {
                        model.NotUseMulArea = decimal.Parse(row.GetCell(6).ToString());
                    }
                    else
                    {
                        model.NotUseMulArea = null;
                    }
                    if (row.GetCell(7) != null && row.GetCell(7).ToString() != "")
                    {
                        model.DestroyMulArea = decimal.Parse(row.GetCell(7).ToString());
                    }
                    else
                    {
                        model.DestroyMulArea = null;
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 添加
        /// </summary>
        public virtual ResResult<int> AddInfo(MulAreaInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_MulAreaStatist";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "NowMulArea,";
            strSql += "IntoMulArea,";
            strSql += "NewPlantMulArea,";
            strSql += "HighMulArea,";
            strSql += "MidMulArea,";
            strSql += "LowMulArea,";
            strSql += "NewlyMulArea,";
            strSql += "NotUseMulArea,";
            strSql += "DestroyMulArea)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@NowMulArea,";
            strSql += "@IntoMulArea,";
            strSql += "@NewPlantMulArea,";
            strSql += "@HighMulArea,";
            strSql += "@MidMulArea,";
            strSql += "@LowMulArea,";
            strSql += "@NewlyMulArea,";
            strSql += "@NotUseMulArea,";
            strSql += "@DestroyMulArea)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    model.Id = CustomFun.GetGuid();
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "添加失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                return obj;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        public virtual ResResult<int> UpdateInfo(MulAreaInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.T_MulAreaStatist set ";
            strSql += "NowMulArea = @NowMulArea,";
            strSql += "IntoMulArea = @IntoMulArea,";
            strSql += "NewPlantMulArea = @NewPlantMulArea,";
            strSql += "HighMulArea = @HighMulArea,";
            strSql += "MidMulArea = @MidMulArea,";
            strSql += "LowMulArea = @LowMulArea,";
            strSql += "NewlyMulArea = @NewlyMulArea,";
            strSql += "NotUseMulArea = @NotUseMulArea,";
            strSql += "DestroyMulArea = @DestroyMulArea";
            strSql += " where ReportId = @ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "更新成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "更新失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("更新表1桑园面积统计表T_MulAreaStatist对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 桑园面积统计--------(按年统计)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulAreaStatsModel>> GetStatsList(MulNowModel model)
        {
            DictServices dictServices = new DictServices();
            if (!string.IsNullOrEmpty(model.FillInYear))
            {
                model.FillInYear = dictServices.GetPZKey(model.FillInYear, "ReportYear");
            }

            string ProvinceCode = "530000000000";
            ResResult<List<MulAreaStatsModel>> result = new ResResult<List<MulAreaStatsModel>>();
            /*县级统计代码*/
            string StrAreaSql = "select case when Area.Code = @AreaCode then Area.Name else  isnull(area2.Name,'云南省') end ParentName ";
            StrAreaSql += ",Area.Code AreaCode, Dict.DictText FillYear, Area.FullName AreaName,Area.Coord ";
            StrAreaSql += ",ISNULL(NowMulArea,0.00) NowMulArea,ISNULL(IntoMulArea,0.00) IntoMulArea";
            StrAreaSql += ",ISNULL(HighMulArea,0.00) HighMulArea,ISNULL(MidMulArea,0.00) MidMulArea";
            StrAreaSql += ",ISNULL(LowMulArea,0.00) LowMulArea,ISNULL(NewlyMulArea,0.00) NewlyMulArea";
            StrAreaSql += ",ISNULL(NotUseMulArea,0.00) NotUseMulArea,ISNULL(DestroyMulArea,0.00) DestroyMulArea";
            StrAreaSql += " from(";
            StrAreaSql += "select ";
            StrAreaSql += "case when grouping(Area.Code) = 1 then @AreaCode else Code end Code, ";
            StrAreaSql += "SUM(ISNULL(MArea.NowMulArea, 0.00))  NowMulArea, ";//--现有面积
            StrAreaSql += "SUM(ISNULL(MArea.IntoMulArea, 0.00)) IntoMulArea, ";// --投产面积
            StrAreaSql += "SUM(ISNULL(MArea.HighMulArea, 0.00)) HighMulArea, ";//--高产面积
            StrAreaSql += "SUM(ISNULL(MArea.MidMulArea, 0.00)) MidMulArea, ";//--中产面积
            StrAreaSql += "SUM(ISNULL(MArea.LowMulArea, 0.00))  LowMulArea, ";//--低产面积
            StrAreaSql += "SUM(ISNULL(MArea.NewlyMulArea, 0.00)) NewlyMulArea, ";//--新栽桑面积
            StrAreaSql += "SUM(ISNULL(MArea.NotUseMulArea, 0.00)) NotUseMulArea,";// --不用于养蚕的桑园面积
            StrAreaSql += "SUM(ISNULL(MArea.DestroyMulArea, 0.00))   DestroyMulArea ";//--挖毁桑园面积
            StrAreaSql += "from([dbo].[T_Report] Report left join T_MulAreaStatist MArea on Report.Id = MArea.ReportId) ";
            StrAreaSql += "right join T_Area Area on Area.Code = Report.AreaCode ";
            StrAreaSql += "where ";
            StrAreaSql += "Area.ParentCode = @AreaCode  and Report.Status=@ReportStatus and Report.FillInYear=@FillInYear  ";
            StrAreaSql += "group by rollup(Area.Code)) tt1 left join T_Area Area on tt1.Code = Area.Code ";
            StrAreaSql += "left join T_Area  area2 on area2.Code = area.ParentCode ";
            StrAreaSql += "inner join T_Dict Dict  on Dict.GroupCode='ReportYear' and DictValue=@FillInYear ";
            StrAreaSql += "where area.ParentCode=@AreaCode  or area.Code=@AreaCode ";
            StrAreaSql += "order by AreaCode asc ";

            /*市级统计代码*/
            string StrCitySql = "select isnull(area2.Name,'云南省') ParentName,Area.Code AreaCode,Dict.DictText FillYear,Area.FullName AreaName,Area.Coord, ";
            StrCitySql += "ISNULL(NowMulArea,0.00) NowMulArea,ISNULL(IntoMulArea,0.00) IntoMulArea,ISNULL(HighMulArea,0.00) HighMulArea,ISNULL(MidMulArea,0.00) MidMulArea,ISNULL(LowMulArea,0.00) LowMulArea,ISNULL(NewlyMulArea,0.00) NewlyMulArea,ISNULL(NotUseMulArea,0.00) NotUseMulArea,ISNULL(DestroyMulArea,0.00) DestroyMulArea ";
            StrCitySql += "from( ";
            StrCitySql += "select ";
            StrCitySql += "case when grouping(Area.ParentCode) = 1 then @AreaCode else ParentCode end ParentCode, ";
            StrCitySql += "SUM(ISNULL(MArea.NowMulArea, 0.00))  NowMulArea, ";// --现有面积
            StrCitySql += "SUM(ISNULL(MArea.IntoMulArea, 0.00)) IntoMulArea, ";//--投产面积
            StrCitySql += "SUM(ISNULL(MArea.HighMulArea, 0.00)) HighMulArea, ";//--高产面积
            StrCitySql += "SUM(ISNULL(MArea.MidMulArea, 0.00)) MidMulArea, ";// --中产面积
            StrCitySql += "SUM(ISNULL(MArea.LowMulArea, 0.00))  LowMulArea, ";// --低产面积
            StrCitySql += "SUM(ISNULL(MArea.NewlyMulArea, 0.00)) NewlyMulArea, ";// --新栽桑面积
            StrCitySql += "SUM(ISNULL(MArea.NotUseMulArea, 0.00)) NotUseMulArea, ";// --不用于养蚕的桑园面积
            StrCitySql += "SUM(ISNULL(MArea.DestroyMulArea, 0.00))   DestroyMulArea  ";//--挖毁桑园面积
            StrCitySql += "from t_report t1  ";
            StrCitySql += "left  join T_MulAreaStatist MArea on MArea.ReportId = t1.Id  ";
            StrCitySql += "right  join T_Area Area on Area.Code = t1.AreaCode  ";
            StrCitySql += "where ParentCode!=@AreaCode  and t1.FillInYear=@FillInYear and t1.Status=@ReportStatus ";
            StrCitySql += "group by rollup(Area.ParentCode)  ";
            StrCitySql += ") t left join T_Area  area on area.Code = t.ParentCode  ";
            StrCitySql += "left join T_Area  area2 on area2.Code = area.ParentCode ";
            StrCitySql += "inner join T_Dict Dict  on Dict.GroupCode = 'ReportYear' and DictValue = @FillInYear  ";
            StrCitySql += "where area.ParentCode=@AreaCode  or area.Code=@AreaCode ";
            StrCitySql += "order by AreaCode asc ";

            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    var paramlist = new DynamicParameters();
                    paramlist.Add("AreaCode", model.AreaCode);
                    paramlist.Add("FillInYear", model.FillInYear);
                    paramlist.Add("ReportStatus", model.Status);
                    List<MulAreaStatsModel> list = new List<MulAreaStatsModel>();
                    if (model.AreaCode != ProvinceCode)//不为省级用户
                    {
                        list = dbCon.Query<MulAreaStatsModel>(StrAreaSql, paramlist).ToList();
                    }
                    else
                    {
                        list = dbCon.Query<MulAreaStatsModel>(StrCitySql, paramlist).ToList();
                    }
                    List<MulAreaStatsModel> list2 = new List<MulAreaStatsModel>();
                    for (var i = 0; i < list.Count; i++)
                    {
                        list2.Add(list[i]);
                    }
                    result.model = list2;
                    //result.model = list;
                    if (list != null)
                    {
                        result.status = DefaultKey.SuccessResult;
                        result.message = "获取蚕桑面积统计数据成功！";
                    }
                    else
                    {
                        result.status = DefaultKey.InfoResult;
                        result.message = "获取蚕桑面积统计数据失败！";
                    }
                    dbCon.Dispose();//数据库连接释放
                }
            }
            catch (Exception ex)
            {
                result.status = DefaultKey.ErrorResult;
                result.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取蚕桑面积统计数据失败", ex);
            }
            return result;
        }
        /// <summary>
        /// 获取时间趋势图数据列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulAreaStatsModel>> GetStatsByTimeList(MulNowModel model)
        {
            DictServices dictServices = new DictServices();
            List<Select> listDict = dictServices.GetListByGroupCode("ReportYear").model;
            ResResult<List<MulAreaStatsModel>> result = new ResResult<List<MulAreaStatsModel>>();
            List<MulAreaStatsModel> list = new List<MulAreaStatsModel>();
            if (listDict.Count > 0)
            {
                if (!string.IsNullOrEmpty(model.AreaCode))
                {
                    for (var i = 0; i < listDict.Count; i++)
                    {
                        model.FillInYear = listDict[i].label;
                        List<MulAreaStatsModel> listOne = GetStatsList(model).model;
                        if (listOne.Count > 0)
                        {
                            list.Add(listOne[0]);
                        }
                    }
                    if (list.Count > 0)
                    {
                        result.message = "时间趋势数据列表获取成功";
                        result.model = list.OrderBy(s => s.FillYear).ToList();
                        result.status = DefaultKey.SuccessResult;
                    }
                    else
                    {
                        result.message = "时间趋势数据列表为空";
                        result.status = DefaultKey.InfoResult;
                    }
                }
                else
                {
                    result.message = "时间趋势数据列表失败,当前地区不存在";
                    result.status = DefaultKey.ErrorResult;
                }
            }
            else
            {
                result.message = "时间趋势数据列表失败,时间为空";
                result.status = DefaultKey.ErrorResult;
            }
            return result;
        }
        public ResResult<List<MulAreaStatsModel>> GetDetailStats(MulNowModel model)
        {
            ResResult<List<MulAreaStatsModel>> res = new ResResult<List<MulAreaStatsModel>>();
            List<MulAreaStatsModel> list = new List<MulAreaStatsModel>();
            string ProvinceCode = DefaultKey.ProvinceCode;
            string FillInYear = model.FillInYear;
            try
            {
                if (model.AreaCode == ProvinceCode)
                {
                    var First = GetStatsList(model).model;
                    //First[0].AreaName = "合计";
                    list.Add(First[0]);//省级汇总合计
                    foreach (var item in First)
                    {
                        if (item.AreaCode != ProvinceCode)
                        {
                            MulNowModel model2 = new MulNowModel();
                            model2.FillInYear = FillInYear;
                            model2.AreaCode = item.AreaCode;
                            model2.Status = model.Status;
                            var Second = GetStatsList(model2).model;
                            list.Add(item);
                            foreach (var item2 in Second)
                            {
                                if (model2.AreaCode != item2.AreaCode)
                                {
                                    list.Add(item2);
                                }
                            }
                        }
                    }
                }
                else
                {
                    list = GetStatsList(model).model;//数据获取
                }
            }
            catch (Exception ex)
            {
                res.model = list;
                res.message = "获取统计数据详情失败" + ex.ToString().Trim();
                res.status = DefaultKey.SuccessResult;
            }
            if (list != null)
            {
                res.model = list;
                res.message = "获取统计数据详情成功";
                res.status = DefaultKey.SuccessResult;
            }
            else
            {
                res.message = "获取统计数据详情成失败";
                res.status = DefaultKey.ErrorResult;
            }
            return res;
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream Method(MulNowModel model)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\Excel.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulAreaStatist") as HSSFSheet;//读取模板所在sheet位置
            MulAreaStatistViewModel pageModel = GetModel(model).model;//数据获取

            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式
            HSSFRow datarow = (HSSFRow)sheet.CreateRow(2);
            datarow.CreateCell(0).SetCellValue(pageModel.NowMulArea == null ? "" : Common.GetOne(pageModel.NowMulArea));
            datarow.CreateCell(1).SetCellValue(pageModel.IntoMulArea == null ? "" : Common.GetOne(pageModel.IntoMulArea));
            datarow.CreateCell(2).SetCellValue(pageModel.NewPlantMulArea == null ? "" : Common.GetOne(pageModel.NewPlantMulArea));
            datarow.CreateCell(3).SetCellValue(pageModel.HighMulArea == null ? "" : Common.GetOne(pageModel.HighMulArea));
            datarow.CreateCell(4).SetCellValue(pageModel.MidMulArea == null ? "" : Common.GetOne(pageModel.MidMulArea));
            datarow.CreateCell(5).SetCellValue(pageModel.LowMulArea == null ? "" : Common.GetOne(pageModel.LowMulArea));
            datarow.CreateCell(6).SetCellValue(pageModel.NewlyMulArea == null ? "" : Common.GetOne(pageModel.NewlyMulArea));
            datarow.CreateCell(7).SetCellValue(pageModel.NotUseMulArea == null ? "" : Common.GetOne(pageModel.NotUseMulArea));
            datarow.CreateCell(8).SetCellValue(pageModel.DestroyMulArea == null ? "" : Common.GetOne(pageModel.DestroyMulArea));
            for (int j = 0; j < 9; j++)
            {
                datarow.GetCell(j).CellStyle = style;
            }
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 导出统计数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream MethodStats(MulNowModel model)
        {
            string FillInYear = model.FillInYear;
            AreaServices areaServices = new AreaServices();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name == "云南省" ? "云南省_县(市、州)" : areaServices.GetByCodeModel(model.AreaCode).model.Name;//获取当前行政区划名称
            getExcelStatsList(workbook, GetDetailStats(model).model, AreaName);//省级汇总(针对曲线)
            if (model.AreaCode == DefaultKey.ProvinceCode)//判断当前用户是否为省级用户
            {
                AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name;
                model.FillInYear = FillInYear;
                getExcelStatsList(workbook, GetStatsList(model).model, AreaName + "_州市");//省级汇总(针对州市)
                var areaList = areaServices.GetPrefectureList();//获取州市级列表
                foreach (var areaCode in areaList)
                {
                    model.AreaCode = areaCode;
                    model.FillInYear = FillInYear;
                    getExcelStatsList(workbook, GetDetailStats(model).model, areaServices.GetByCodeModel(areaCode).model.Name);
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 返回excel工作簿
        /// </summary>
        /// <param name="workbook">工作簿</param>
        /// <param name="sheet">子表</param>
        /// <param name="model"></param>
        /// <param name="AreaName">地区名称</param>
        /// <returns></returns>
        public HSSFWorkbook getExcelStatsList(HSSFWorkbook workbook, List<MulAreaStatsModel> list, string AreaName)
        {
            try
            {
                FileStream file = null;
                string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
                string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
                string tempExcel = fileIndex + filename;//临时文件路径及全称
                string templateName = fileIndex + @"Excel\ExcelStats.xls";//模板文件
                file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
                HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
                HSSFSheet sheet = templateBook.GetSheet("MulAreaStatist") as HSSFSheet;//读取模板所在sheet位置
                IDataFormat format = templateBook.CreateDataFormat();//创建格式化 实例对象
                #region 县市级表格样式
                HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
                var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
                //style.DataFormat = format.GetFormat("#,##0.0");
                #endregion
                //row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式
                #region 州市级表格样式
                var styleOneCity = Common.GetOneCityCellStyle(templateBook, style);
                var styleOneArea = Common.GetOneAreaCellStyle(templateBook, style);

                #endregion
                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 2);
                        datarow.CreateCell(0).SetCellValue(list[i].AreaName == null ? "" : list[i].AreaName.ToString());
                        datarow.CreateCell(1).SetCellValue(list[i].NowMulArea == null ? 0.0 : Convert.ToDouble(list[i].NowMulArea));
                        datarow.CreateCell(2).SetCellValue(list[i].IntoMulArea == null ? 0.0 : Convert.ToDouble(list[i].IntoMulArea));
                        //datarow.CreateCell(3).SetCellValue(list[i].NewPlantMulArea == null ? "" : Math.Round((double)list[i].NewPlantMulArea, 1).ToString());
                        datarow.CreateCell(3).SetCellValue(list[i].HighMulArea == null ? 0.0 : Convert.ToDouble(list[i].HighMulArea));
                        datarow.CreateCell(4).SetCellValue(list[i].MidMulArea == null ? 0.0 : Convert.ToDouble(list[i].MidMulArea));
                        datarow.CreateCell(5).SetCellValue(list[i].LowMulArea == null ? 0.0 : Convert.ToDouble(list[i].LowMulArea));
                        datarow.CreateCell(6).SetCellValue(list[i].NewlyMulArea == null ? 0.0 : Convert.ToDouble(list[i].NewlyMulArea));
                        datarow.CreateCell(7).SetCellValue(list[i].NotUseMulArea == null ? 0.0 : Convert.ToDouble(list[i].NotUseMulArea));
                        datarow.CreateCell(8).SetCellValue(list[i].DestroyMulArea == null ? 0.0 : Convert.ToDouble(list[i].DestroyMulArea));
                        if (CustomFun.IsCity(list[i].AreaCode))
                        {//省级和州市级
                            for (int j = 0; j < 9; j++)
                            {
                                datarow.GetCell(j).CellStyle = styleOneCity;
                            }
                        }
                        else//县级
                        {
                            for (int j = 0; j < 9; j++)
                            {
                                datarow.GetCell(j).CellStyle = styleOneArea;
                            }
                        }

                    }
                    sheet.CopyTo(workbook, AreaName, true, true);

                }
            }
            catch (Exception ex)//捕捉异常
            {

            }
            return workbook;
        }
    }
}